/**
 * InputView.js
 * 
 * 负责渲染和管理用户输入区域，包括文本输入、发送按钮、附件列表等。
 */


(function() {
    class InputView {
        constructor(handlers) {
            this.handlers = handlers;
            this.input = document.getElementById('user-input');
            this.sendBtn = document.getElementById('send-button');
            this.attachArea = document.getElementById('attachments-list');
            this.attachContainer = document.getElementById('attachments-area'); // 获取容器引用
            this.files = [];

            this._bindEvents();
        }

        _bindEvents() {
            if(this.sendBtn) this.sendBtn.addEventListener('click', () => this._triggerSend());
            if(this.input) this.input.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this._triggerSend();
                }
            });
        }

        _triggerSend() {
            const text = this.input.value.trim();
            if (!text && this.files.length === 0) return;
            
            this.handlers.onSend(text, [...this.files]);
            
            this.input.value = '';
            this.clearAttachments();
        }

        addAttachment(file) {
            if (this.files.some(f => f.path === file.path)) return;
            this.files.push(file);
            this._renderAttachments();
        }

        clearAttachments() {
            this.files = [];
            this._renderAttachments();
        }

        _renderAttachments() {
            if (!this.attachArea || !this.attachContainer) return;

            this.attachArea.innerHTML = '';
            // 根据是否有文件来控制容器显示
            this.attachContainer.style.display = this.files.length ? 'block' : 'none';
            
            this.files.forEach((file, index) => {
                const div = document.createElement('div');
                div.className = 'attachment-item'; 
                div.title = file.path;
                
                // 构建符合 CSS 预期的 HTML 结构
                div.innerHTML = `
                    <span class="codicon codicon-file"></span>
                    <span class="attachment-name">${file.name}</span>
                    <span class="codicon codicon-close attachment-remove"></span>
                `;
                
                // 绑定删除事件
                div.querySelector('.attachment-remove').onclick = (e) => {
                    e.stopPropagation();
                    this.files.splice(index, 1);
                    this._renderAttachments();
                };
                
                this.attachArea.appendChild(div);
            });
        }
    }

    window.InputView = InputView;
})();